package com.governtalk.backend.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.governtalk.backend.service.CozeFileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Service
public class CozeFileUploadServiceImpl implements CozeFileUploadService {

    @Value("${ai.coze.api-key:default-api-key}")
    private String apiKey;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String uploadFileToCoze(MultipartFile file) {
        System.out.println("=== 开始上传文件到Coze平台 ===");
        System.out.println("文件名: " + file.getOriginalFilename());
        System.out.println("文件大小: " + file.getSize() + " 字节");
        System.out.println("文件类型: " + file.getContentType());

        try {
            // Coze文件上传API端点
            URL url = new URL("https://api.coze.cn/open_api/v2/file/upload");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setDoOutput(true);

            // 构建multipart/form-data请求
            String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            try (OutputStream outputStream = connection.getOutputStream()) {
                // 写入文件部分
                outputStream.write(("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8));
                outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + 
                    file.getOriginalFilename() + "\"\r\n").getBytes(StandardCharsets.UTF_8));
                outputStream.write(("Content-Type: " + file.getContentType() + "\r\n\r\n").getBytes(StandardCharsets.UTF_8));
                
                // 写入文件内容
                try (java.io.InputStream inputStream = file.getInputStream()) {
                    byte[] buffer = new byte[8192];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
                
                // 结束边界
                outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            System.out.println("Coze文件上传响应码: " + responseCode);

            String responseBody;
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    responseBody = response.toString();
                }
            } else {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    responseBody = response.toString();
                }
            }

            System.out.println("Coze文件上传响应: " + responseBody);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                JsonNode jsonResponse = objectMapper.readTree(responseBody);
                if (jsonResponse.has("data") && jsonResponse.get("data").has("id")) {
                    String fileId = jsonResponse.get("data").get("id").asText();
                    System.out.println("✅ 文件上传成功，文件ID: " + fileId);
                    return fileId;
                } else {
                    throw new RuntimeException("响应中未找到文件ID: " + responseBody);
                }
            } else {
                throw new RuntimeException("文件上传失败，响应码: " + responseCode + ", 响应: " + responseBody);
            }

        } catch (IOException e) {
            System.err.println("❌ 文件上传到Coze失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("文件上传到Coze失败: " + e.getMessage(), e);
        }
    }
}
